(function() {

    function extractParams(extractPatterns, text, params) {
        for (var key in extractPatterns) {
            var result = extractPatterns[key].exec(text);
            if (result) {
                params[key] = result[1];
            }
        }
    }

    function extractFacebookParams(session) {

        var fbPatterns = {
            "api_key": /api_key=([^&]+)&/i,
            "fb_sig_time": /fb_sig_time=([^&]+)&/i,
            "fb_sig_session_key": /fb_sig_session_key=([^&]+)&/i,
            "fb_sig_profile_update_time": /fb_sig_profile_update_time=([^&]+)&/i,
            "fb_sig_app_id": /fb_sig_app_id=([^&]+)&/i,
            "fb_sig_user": /fb_sig_user=([^&]+)&/i,
            "fb_sig_ss": /fb_sig_ss=([^&]+)&/i,
            "fb_sig_expires": /fb_sig_expires=([^&]+)&/i,
            "fb_sig_ext_perms": /fb_sig_ext_perms=([^&]+)&/i,
            "fb_sig_cookie_sig": /fb_sig_cookie_sig=([^&]+)&/i,
            "fb_sig": /fb_sig=([^&]+)&/i,
            "fb_sig_api_key": /fb_sig_api_key=([0-9a-z]+?)/i
        };

        var url = document.URL;

        extractParams(fbPatterns, url, session);
    }

    function extractPlayfishParams(session) {

        var pfPatterns = {
            "pf_senderId": /pf_senderId=(\d+)/i,
            "pf_giftItemId": /pf_giftItemId=(\d+)/i,
            "pf_session_key": /name="pf_session_key" value="([^"]+)"/i,
            "pf_api_key": /name="pf_api_key" value="([^"]+)"/i,
            "pf_giftToken": /name="pf_giftToken" value="([^"]+)"/i
        };

        var html = document.documentElement.innerHTML;

        extractParams(pfPatterns, html, session);
    }

    function main() {

        var session = {
            "status": "session"
        };

        extractFacebookParams(session);
        extractPlayfishParams(session);

        // send session data to background page
        chrome.extension.sendRequest(session);
    }

    main();

})();
